package com.campus.dao.impl;

import com.campus.dao.UserDao;
import com.campus.model.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    private final JdbcTemplate jdbcTemplate;

    public UserDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public User login(String loginName, String password) {
        String sql = "SELECT * FROM users WHERE LOWER(login_name) = LOWER(?)";
        try {
            User user = jdbcTemplate.queryForObject(sql, new Object[]{loginName},
                    new BeanPropertyRowMapper<>(User.class));
            System.out.println("Input password: " + password);
            System.out.println("Stored password: " + (user != null ? user.getPassword() : null));
            if (user != null && password.equals(user.getPassword())) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addUser(User user) {
        String sql = "INSERT INTO users (login_name, password, gender, birthday, phone, email, status) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, user.getLoginName(), user.getPassword(), user.getGender(),
                user.getBirthday(), user.getPhone(), user.getEmail(), user.getStatus());
    }


    @Override
    public int updateUser(User user) {
        String sql = "UPDATE users SET login_name = ?, password = ?, gender = ?, birthday = ?, phone = ?, " +
                "email = ?, status = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getLoginName(), user.getPassword(), user.getGender(),
                user.getBirthday(), user.getPhone(), user.getEmail(), user.getStatus(), user.getId());
    }

    @Override
    public List<User> queryUser(String keyword) {
        String sql = "SELECT * FROM users WHERE login_name LIKE ? OR id = ?";
        return jdbcTemplate.query(sql, new Object[]{"%" + keyword + "%", keyword},
                new BeanPropertyRowMapper<>(User.class));
    }
}
